<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 政府办事指南
 * Class government
 * @author heyu
 */
class Government extends MY_Controller {
    public $mGovernment;

	public function __construct(){
		parent::__construct();
		$this->loadModel('AdmGovernmentModel', 'mGovernment');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $data = array(
            'title' => '政府办事指南'
        );
		$this->view('shop/government/home', $data, 'datatable,validation,datepicker');
	}

    /**
     * 获取数据
     */
    public function getList(){
        $data = $this->mGovernment->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '<img width="100%" src="'.getImage($v['logo'],'xs').'" class="img-wh"/>';
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['tel'];
            $data['aaData'][$k][] = $v['address'];
            $data['aaData'][$k][] = $v['latitude'].','.$v['longitude'];
            $data['aaData'][$k][] = $v['read_number'];
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $btnConfig = adminCreateBtn(array(
                    'label' => ' 详情',
                    'attr' => array(
                        'href' => getUrl('shop/government/details').'?id='.$v['id'],
                        'class' => 'btn btn-xs green-stripe default edit-btn',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'group',
                        'key' => 'edit'
                    )
                ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('shop/government/edit').'?id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'group',
                        'key' => 'edit'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 详情
     */
    public function details(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mGovernment->getInfo($id);
        if (!$info){
            show_404();
        }
        $data = array(
            'info' => $info,
            'title' => '详情'
        );
        $this->view('shop/government/details', $data, 'datatable,validation,datepicker,ueditor,webuploader');
    }

    /**
     * 添加
     */
    public function add(){
        $data = array(
            'add' => true,
            'title' => '添加'
        );
        $this->view('shop/government/from', $data, 'validation,webuploader,cropit_master');
    }

    /**
     * 编辑
     */
    public function edit(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mGovernment->getInfo($id);
        $data = array(
            'info' => $info,
            'add' => false,
            'title' => '编辑'
        );
        $this->view('shop/government/from', $data, 'validation,webuploader,cropit_master');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('name', '政府名称', 'required'),
            array('tel', '政府电话', 'required'),
            array('address', '地址', 'required'),
            array('latitude', '经度', 'required'),
            array('longitude', '维度', 'required'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');
        $title = post('title');
        $mobile = post('mobile');
        $branch = array();
        if (!empty($title)){
            if (count($title) != count($mobile)){
                $this->ajaxReturn(0, '部门信息错误');
            }
            $branch = array();
            foreach ($title as $k => $v){
                if (isset($v) && isset($mobile[$k])){
                    if (strlen($mobile[$k]) < 7){
                        $this->ajaxReturn(0, '部门电话错误');
                    }
                    $branch[] = array(
                        'title' => $v,
                        'mobile' => $mobile[$k]
                    );
                }
            }
        }

        $data = array(
            'name' => trim(post('name')),
            'tel' => trim(post('tel')),
            'address' => trim(post('address')),
            'latitude' => trim(post('latitude')),
            'longitude' => trim(post('longitude')),
            'branch' => json_encode($branch, JSON_UNESCAPED_UNICODE),
        );
        $this->db->trans_begin();
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($id = $this->mGovernment->save($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mGovernment->getInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '数据不存在');
            }
        }
        $path = 'uploads/government/'.$id.'/logo/';
        $logo = post('logo');
        if ($logo){
            $tA = saveCSVimg(array($logo), $path, 'logo');
            if( ! $tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, 'logo上传失败');
            }

            $data['logo'] = $tA[0];

        }
        $pathPic = 'uploads/government/'.$id.'/pic/';
        $images = post('pic');

        foreach ($images as $k => $v){
            $tA = explode('?', str_replace(base_url(), '', $v));
            $picImg = $tA[0];

            if (!file_exists($picImg)) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '轮播图片错误1');
            }
            $picImg = imageThumb($picImg, $pathPic, 750, 350);

            if (!$picImg) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '轮播图片错误2');
            }
            $data['pic'][] = $picImg;
        }
        $data['pic'] = json_encode($data['pic'], JSON_UNESCAPED_UNICODE);
        if( ! $this->mGovernment->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', null, getUrl('shop/government'));
    }

    /**
     * 保存部门信息
     */
    public function saveBranch(){
        $id = (int)post('id');
        $title = post('title');
        $mobile = post('mobile');
        $branch = array();
        if (!empty($title)){
            if (count($title) != count($mobile)){
                $this->ajaxReturn(0, '部门信息错误');
            }
            $branch = array();
            foreach ($title as $k => $v){
                if (isset($v) && isset($mobile[$k])){
                    if (strlen($mobile[$k]) < 7){
                        $this->ajaxReturn(0, '部门电话错误');
                    }
                    $branch[] = array(
                        'title' => $v,
                        'mobile' => $mobile[$k]
                    );
                }
            }
        }
        $info = $this->mGovernment->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $data = array(
            'branch' => json_encode($branch, JSON_UNESCAPED_UNICODE),
        );
        if( ! $this->mGovernment->save($data, $id)){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 保存轮播图
     */
    public function saveImage(){
        $id = (int)post('id');
        $info = $this->mGovernment->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }

        $pathPic = 'uploads/government/'.$id.'/pic/';
        $pathPicXs = 'uploads/government/'.$id.'/pic/xs/';
        $images = post('pic');
        $data = array();
        foreach ($images as $k => $v){
            $tA = explode('?', str_replace(base_url(), '', $v));
            $picImg = $tA[0];

            if (!file_exists($picImg)) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '轮播图片错误1');
            }
            $picImg = imageThumb($picImg, $pathPic, 500, 500);
            imageThumb($picImg, $pathPicXs, 150, 150);

            if (!$picImg) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '轮播图片错误2');
            }
            $data['pic'][] = $picImg;
        }

        $data['pic'] = json_encode($data['pic'], JSON_UNESCAPED_UNICODE);
        if( ! $this->mGovernment->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 获取部门信息
     */
    public function getBranchList(){
        $id = (int)post('id');
        if (!$id){
            $this->ajaxReturn(0, '参数有误');
        }
        $info = $this->mGovernment->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $this->ajaxReturn(1, '', $info['branch']);
    }

    /**
     * 获取申报信息列表
     */
    public function getDeclareLogList(){
        $id = (int)get('id');
        if (!$id){
            $this->ajaxReturn(0, '数据错误');
        }
        $data = $this->mGovernment->adminPcGetDeclareLogList($id);
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['id'];
            $data['aaData'][$k][] = $v['title'];
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => ' 编辑',
                'attr' => array(
                    'href' => 'javascript:;',
                    'class' => 'btn-edit btn btn-xs blue-stripe default',
                    'data-id' => $v['id'],
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'group',
                    'key' => 'edit'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 获取信息详情
     */
    public function getDeclareLogInfo(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mGovernment->getDeclareLogInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $this->ajaxReturn(1, '', $info);
    }

    /**
     * 保存申报信息
     */
    public function saveDeclareLog(){
        //表单验证
        $vConf = array(
            array('title', '标题', 'required'),
            array('content', '内容', 'required'),
            array('government_id', '政府部门id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $government_id = (int)post('government_id');
        $info = $this->mGovernment->getInfo($government_id);
        if (!$info){
            $this->ajaxReturn(0, '政府办事指南数据不存在');
        }
        $data = array(
            'title' => trim(post('title')),
            'content' => post('content'),
            'government_id' => $government_id
        );
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($rs = $this->mGovernment->saveDeclareLog($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mGovernment->getDeclareLogInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '数据不存在');
            }
            $rs = $this->mGovernment->saveDeclareLog($data,$id);
        }
        if (!$rs){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 获取区县列表
     */
    public function getDistrictList(){
        $id = (int)post('id');
        if (!$id){
            $this->ajaxReturn(0, '数据错误');
        }
        $data = $this->mGovernment->adminPcGetDistrictList($id);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取区县详情
     */
    public function getDistrictInfo(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mGovernment->getDistrictInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $this->ajaxReturn(1, '', $info);
    }

    /**
     * 保存区县信息
     */
    public function saveDistrict(){
        //表单验证
        $vConf = array(
            array('district_name', '区县名称', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $government_id = (int)post('g_id');
        $info = $this->mGovernment->getInfo($government_id);
        if (!$info){
            $this->ajaxReturn(0, '政府办事指南数据不存在');
        }
        $addressArr = array();
        $bureauAddress = post('bureau_address');
        $bureauTel = post('bureau_tel');
        $bureauLatLng = post('bureau_lat_lng');
        $countyAddress = post('county_address');
        $countyTel = post('county_tel');
        $countyLatLng = post('county_lat_lng');

        $i = 0;
        // 县局
        if (!empty($bureauAddress)) {
            if (count($bureauAddress) != count($bureauTel)) {
                $this->ajaxReturn(0, '县局地址获取电话错误');
            }
            foreach ($bureauAddress as $k => $v) {
                if (isset($v) && $bureauTel[$k]) {
                    $arr = explode($bureauTel[$k], '-');
                    foreach ($arr as $kk => $vv) {
                        if (is_numeric($vv)) {
                            $this->ajaxReturn(0, '请填写正确的电话号码');
                        }
                    }
                    $addressArr[$i]['type'] = '县局';
                    $latLng = explode(',', $bureauLatLng[$k]);
                    $addressArr[$i]['address'][$k] = array(
                        'address' => $v,
                        'lat' => $latLng[0],
                        'lng' => $latLng[1],
                        'tel' => $bureauTel[$k],
                    );
                }
            }
            if (!empty($addressArr)) $i+=1;
        }

        // 县所
        if (!empty($countyAddress)) {
            if (count($countyAddress) != count($countyTel)) {
                $this->ajaxReturn(0, '县所地址获取电话错误');
            }
            foreach ($countyAddress as $kk => $vv) {
                if (isset($vv) && $countyTel[$kk]) {
                    $arr = explode($countyTel[$kk], '-');
                    foreach ($arr as $kkk => $vvv) {
                        if (is_numeric($vvv)) {
                            $this->ajaxReturn(0, '请填写正确的电话号码');
                        }
                    }
                    $addressArr[$i]['type'] = '县所';
                    $latLng = explode(',', $countyLatLng[$kk]);
                    $addressArr[$i]['address'][$kk] = array(
                        'address' => $vv,
                        'lat' => $latLng[0],
                        'lng' => $latLng[1],
                        'tel' => $countyTel[$kk],
                    );
                }
            }
        }
        $data = array(
            'district_name' => trim(post('district_name')),
            'government_id' =>$government_id,
            'address' => json_encode($addressArr, JSON_UNESCAPED_UNICODE)
        );

        if( ! $id){
            $data['addtime'] = time();
            if( ! ($rs = $this->mGovernment->saveDistrict($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mGovernment->getDistrictInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '数据不存在');
            }
            $rs = $this->mGovernment->saveDistrict($data,$id);
        }
        if (!$rs){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功', '', getUrl('shop/government/details?id='.$government_id));
    }

    /**
     * 删除区县信息
     */
    public function deleteDistrict(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mGovernment->getDistrictInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在或已删除');
        }
        $tA = $this->mGovernment->deleteDistrict($id);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 添加六县
     */
    public function districtAdd(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mGovernment->getInfo($id);
        if (!$info){
            show_404();
        }

        $data = array(
            'info' => $info,
            'add' => true,
            'title' => '添加六县 - '.$info['name'],
            'backUrl' => getUrl('shop/government/details?id='.$id)
        );
        $this->view('shop/government/district', $data, 'datatable,validation,datepicker,ueditor,webuploader');
    }

    public function districtEdit(){
        $id = (int)get('id');
        $district = (int)get('district'); // 六县id
        if (!$id || !$district){
            show_404();
        }
        $i = $this->mGovernment->getInfo($id);
        if (!$i){
            show_404($i);
        }
        $info = $this->mGovernment->getDistrictInfo($district);
        if (!$info){
            show_404();
        }
        $data = array(
            'info' => $info,
            'add' => false,
            'title' => '编辑六县 - '.$i['name'],
            'backUrl' => getUrl('shop/government/details?id='.$id)
        );
        $this->view('shop/government/district', $data, 'datatable,validation,datepicker,ueditor,webuploader');
    }

    /**
     * 删除
     */
    public function delete(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mgovernment->getInfo($id, true);
        if (!$info){
            $this->ajaxReturn(0, '新闻不存在或已删除');
        }
        $tA = $this->mgovernment->deletegovernment($id);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }
}
